package com.cy.ppj.service.account.impl;

import com.cy.ppj.comm.constant.CacheConstants;
import com.cy.ppj.comm.utils.CommonUtils;
import com.cy.ppj.comm.utils.SpringELUtils;
import com.cy.ppj.dao.mapper.account.CommissionMapper;
import com.cy.ppj.dao.mapper.account.CommissionRecordMapper;
import com.cy.ppj.dao.mapper.account.StatisticsUserCommissionMapper;
import com.cy.ppj.dao.mapper.account.TeamCommissionMapper;
import com.cy.ppj.model.CacheBean;
import com.cy.ppj.model.PageBean;
import com.cy.ppj.model.Result;
import com.cy.ppj.model.domian.order.CommissionRecord;
import com.cy.ppj.model.domian.statistics.StatisticsUserCommission;
import com.cy.ppj.model.dto.account.AccountAmountDTO;
import com.cy.ppj.model.query.CommissionRecordQuery;
import com.cy.ppj.model.query.commission.CommissionRecordAdminQuery;
import com.cy.ppj.model.vo.CommissionRecordVO;
import com.cy.ppj.model.vo.admin.commission.CommissionRecordAdminVO;
import com.cy.ppj.model.vo.admin.order.OrderCommissionAdminStatisticsVO;
import com.cy.ppj.model.vo.front.account.CommissionInfoVO;
import com.cy.ppj.model.vo.front.account.CommissionStatisticsVO;
import com.cy.ppj.service.BaseService;
import com.cy.ppj.service.account.AccountService;
import com.cy.ppj.service.account.CommissionRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: 佣金
 * @author: Ocean
 * @create: 2018-08-03 20:09
 **/
@Slf4j
@Service
public class CommissionRecordServiceImpl extends BaseService implements CommissionRecordService {

    @Autowired
    private CommissionRecordMapper commissionRecordMapper;
    @Autowired
    private AccountService accountService;
    @Autowired
    private CommissionMapper commissionMapper;
    @Autowired
    private TeamCommissionMapper teamCommissionMapper;
    @Autowired
    private StatisticsUserCommissionMapper statisticsUserCommissionMapper;

    @Override
    @Transactional
    public void addComissionRecord(CommissionRecord commissionRecord) {

        String remark = SpringELUtils.getValue(commissionRecord.getType().getExpression(), commissionRecord.getRemarkObject());
        commissionRecord.setRemark(remark);
        commissionRecordMapper.insertSelective(commissionRecord);

        //维护佣金数据
        int result = commissionMapper.addAmount(commissionRecord.getUserId(), commissionRecord.getAmount());
        state(result == 1, "维护系统佣金异常");

        //维护统计数据
        StatisticsUserCommission statisticsUserCommission = new StatisticsUserCommission();
        statisticsUserCommission.setAmount(commissionRecord.getAmount());
        statisticsUserCommission.setUserId(commissionRecord.getUserId());
        statisticsUserCommission.setType(commissionRecord.getType());
        statisticsUserCommission.setCreateTime(commissionRecord.getCreateTime());
        statisticsUserCommissionMapper.insertStatisticsUserCommission(statisticsUserCommission);

        if (commissionRecord.getTeamUserId() != null) {
            //如果有团队用户ID，记录团队佣金
            result = teamCommissionMapper.addAmount(commissionRecord.getUserId(), commissionRecord.getTeamUserId(), commissionRecord.getAmount());
            state(result == 1, "更新团队佣金异常");
        }

        if (commissionRecord.getDealType() != null) {
            //做交易记录
            AccountAmountDTO accountAmountDTO = new AccountAmountDTO();
            accountAmountDTO.setUpdateTime(commissionRecord.getCreateTime());
            accountAmountDTO.setUserId(commissionRecord.getUserId());
            accountAmountDTO.setAmount(commissionRecord.getAmount());
            accountAmountDTO.setType(commissionRecord.getDealType());
            accountAmountDTO.setRelationId(commissionRecord.getOrderId());
            String dealRemark = SpringELUtils.getValue(commissionRecord.getDealType().getExpression(), commissionRecord.getRemarkObject());
            accountAmountDTO.setRemark(dealRemark);
            accountService.transaction(accountAmountDTO);
        }
    }

    @Override
    public OrderCommissionAdminStatisticsVO statistics() {
        OrderCommissionAdminStatisticsVO vo = commissionRecordMapper.selectOrderCommissionAdminStatistics();
        return vo;
    }

    @Override
    public PageBean<CommissionRecordVO> commissionRecord(CommissionRecordQuery commissionRecordQuery) {
        int total = commissionRecordMapper.selectCommissionRecordCount(commissionRecordQuery);
        List<CommissionRecordVO> list = new ArrayList<>();
        if (total > 0) {
            commissionRecordQuery.startPage();
            list = commissionRecordMapper.selectCommissionRecord(commissionRecordQuery);
            list.forEach(c -> {
                c.setTypeText(c.getType().getText());
            });
        }
        return new PageBean<>(list, total);
    }

    @Override
    public CommissionInfoVO queryUserCommissionInfo(Long userId) {
        Date startTime = CommonUtils.getMonthStartTime(new Date());
        Date endTime = CommonUtils.getMonthEndTime(startTime);
        return commissionRecordMapper.selectUserCommissionInfo(userId, startTime, endTime);
    }

    @Override
    public CommissionInfoVO queryUserCommissionInfo2(Long userId) {

        return commissionRecordMapper.selectUserCommissionInfo2(userId);
    }

    @Override
    @Cacheable(value = CacheConstants.CACHE_VALUE_1H, key = "'commissionStatistics-'+#userId")
    public CacheBean<CommissionStatisticsVO> commissionStatistics(Long userId, Date time) {

        //今天的开始时间
        Date endTime = CommonUtils.getDayEndTime(time);
        //半年前的时间
        Date startTime = CommonUtils.addTime(endTime, -5, Calendar.MONTH);
        //转换为当月第一天
        startTime = CommonUtils.getMonthStartTime(startTime);

        List<CommissionStatisticsVO> list = commissionRecordMapper.selectCommissionStatisticsByUserId(userId, startTime, endTime);
        List<CommissionStatisticsVO> tempList = new ArrayList<>();
        if (list.size() < 6) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startTime);
            int startMonth = calendar.get(Calendar.MONTH) + 1;
            int startYear = calendar.get(Calendar.YEAR);
            for (int i = 0; i < 6; i++) {
                int temp = startMonth + i;
                int month = temp > 12 ? 1 : temp;
                if (temp > 12) {
                    startYear++;
                }
                if (list.stream().noneMatch(c -> Integer.valueOf(month).equals(c.getMonth()))) {
                    CommissionStatisticsVO commissionStatistics = new CommissionStatisticsVO();
                    commissionStatistics.setYear(startYear);
                    commissionStatistics.setMonth(month);
                    commissionStatistics.setAmount(new BigDecimal("0"));
                    tempList.add(commissionStatistics);
                }
            }
            list.addAll(tempList);
            list = list.stream().sorted((a, b) -> {
                if (a.getYear().equals(b.getYear())) {
                    return a.getMonth().compareTo(b.getMonth());
                } else {
                    return a.getYear().compareTo(b.getYear());
                }
            }).collect(Collectors.toList());

        }
        CacheBean<CommissionStatisticsVO> cacheBean = new CacheBean<>();
        cacheBean.setCacheTime(time);
        cacheBean.setList(list);
        return cacheBean;
    }

	@Override
	public PageBean<CommissionRecordAdminVO> selectCommissionRecordAdminList(CommissionRecordAdminQuery query) {
		int total = commissionRecordMapper.selectCommissionRecordAdminCount(query);
		List<CommissionRecordAdminVO> list = new ArrayList<>();
		if(total > 0) {
			query.startPage();
			list = commissionRecordMapper.selectCommissionRecordAdminList(query);
			list.stream().forEach(c -> {
				c.setTypeRemark(c.getType().getText());
				c.setCommissionRateText(String.valueOf(c.getCommissionRate()).concat("%"));
			});
		}
		return new PageBean<>(list, total);
	}
}
